package main

import (
	"bufio"
	"fmt"
	"net"
)

var (
	conn net.Conn
)

func (conn net.Conn,err error) InitConn(comm_type string,bank_ip_msg string)
{
	err:=nil
	
	conn, err := net.Dial(comm_type, bank_ip_msg)
	
	if err!=nil {
        fmt.Println("服务端连接失败,原因:%s",err);
    }
	
	return err
}


func (snd_number int,err error) send_bank_msg(bank_msg byte[], conn net.Conn) {
	client.Write(bank_msg);
}

func (length int,err error)rev_bank_msg(byte[] rev_msg)
{
	
}

func disConnect(conn net.Conn)
{
	conn.Close()
}







//listen handle
func (cli *CliInfo) listenHandle(clientID int) {
	headBuff := make([]byte, 12) // set read stream size
	defer cli.Conn.Close()

	//send verify Key：
	b := []byte(cli.VerifyKey)
	cli.Conn.Write(b)
	// fmt.Println("cli-IP:", cli.Conn.RemoteAddr().String())

	//await 1 second verify
	cli.Conn.SetDeadline(time.Now().Add(time.Duration(1) * time.Second))

	forControl := true
	for forControl {
		var headNum int
		for headNum < cap(headBuff) {
			readHeadNum, readHeadErr := cli.Conn.Read(headBuff[headNum:])
			if readHeadErr != nil {
				log.Println("errHead:", readHeadErr)
				forControl = false
				break
			}
			headNum += readHeadNum
		}
		if headNum == cap(headBuff) {
			//pack head Handle
			packHead := packHeadAnalysis(headBuff) //get length & command
			bodyBuff := make([]byte, packHead.PackLen)
			var bodyNum int
			for bodyNum < cap(bodyBuff) {
				readBodyNum, readBodyErr := cli.Conn.Read(bodyBuff[bodyNum:])
				if readBodyErr != nil {
					log.Println("errBody:", readBodyErr)
					forControl = false
					break
				}
				bodyNum += readBodyNum
			}
			if bodyNum == int(packHead.PackLen) {
				//pack body Handle
				cli.packBodyAnalysis(clientID, packHead, bodyBuff)
				// fmt.Printf("packType:%d;packOther:%d;packLen:%d\n", packHead.PackType, packHead.PackOther, packHead.PackLen)
			}
		}
	}
	cli.disconnect(clientID)
}
